package com.dofuntech.dataplatform.protocal;

import com.dofuntech.dataplatform.util.ByteEncoder;

import org.apache.mina.core.buffer.IoBuffer;

import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

/**
 * �ɹ���Ϣ��
 * <p>
 *
 * @author DavidChen
 */
public class SuccessBody extends MessageBody<SuccessBody> {

    private String message;

    SuccessBody() {

    }

    public SuccessBody(String message) {
        this.message = message;
    }

    @Override
    public Command command() {
        return Command.SUCCESS;
    }

    @Override
    public void writeTo(IoBuffer encoder) throws IOException {
        writeOrCountBytes(encoder, false);
    }



    @Override
    public SuccessBody decode(byte[] buffer, int offset, int byteCount) {
        if (byteCount > 0) {
            message = ByteEncoder.readString(buffer, offset, byteCount);
        }
        return this;
    }

    private int writeOrCountBytes(IoBuffer encoder, boolean countBytes) {
        int start = 0 ;


        if (message == null || message.length() == 0) {
            return 0;
        }

        try {
            encoder.putString (message+"\0", Charset.forName("GBK").newEncoder());
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }


        contentSize = encoder.position() - start;

        return contentSize;
    }

    @Override
    public String toString() {
        return "--�����ɹ�--,��Ϣ����" + getContentLength() + ",��Ϣ��" + (message == null ? "" : message);
    }

    public String getMessage() {
        return message;
    }

}
